const mongoose = require('mongoose')
const db = 'mongodb://localhost:27017/my-movies'
const glob = require('glob')
const { resolve } = require('path')

mongoose.Promise = global.Promise

exports.initSchemas = () => {
    glob.sync(resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}

exports.initAdmin = async () => {
    const Admin = mongoose.model('Admin')
    let admin = await Admin.findOne({
        adminname: 'lushiyu'
    })

    if (!admin) {
        const admin = new Admin({
            adminname: 'lushiyu',
            email: '1307221817@qq.com',
            password: '12345678'
        })
        await admin.save()
    }
}

exports.connect = () => {
    let maxConnectTimes = 0

    return new Promise((resolve, reject) => {
        if (process.env.NODE_ENV !== 'production') {
            mongoose.set('debug', true)
        }

        mongoose.connect(db)

        mongoose.connection.on('disconnected', () => {
            maxConnectTimes++

            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了1')
            }
        })

        mongoose.connection.on('error', err => {
            console.log(err)
            maxConnectTimes++

            if (maxConnectTimes < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了2')
            }
        })

        mongoose.connection.on('open', () => {
            // const Dog = mongoose.model('Dog', { name: String })
            // const doga = new Dog({ name: 'aaaaa' })
            // doga.save().then(()=>{
            //     console.log('wang')
            // })
            resolve()
            console.log('MongoDB Connected successfully!')
        })
    })
}